package com.cmys.money.cloudshop.controller.product;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.cmys.money.cloudshop.model.product.Brand;
import com.cmys.money.cloudshop.model.product.ProductInfo;
import com.cmys.money.cloudshop.service.product.ProductService;
import com.cmys.money.cloudshop.util.file.FileBean;
import com.cmys.money.cloudshop.util.file.FileUtils;
import com.cmys.money.cloudshop.util.properties.PropertiesUtils;

@Controller
@RequestMapping("/app/product") 
public class ProductController {
	
    private static final Logger logger = Logger.getLogger(ProductController.class);
    private final ProductService productService;
    
    @Autowired
    public ProductController(ProductService productService) {
		super();
		this.productService = productService;
	}
    
    @RequestMapping(value = "/add/brand", method = RequestMethod.GET)
	public void addBrand() {
    	Brand brand = new Brand();
    	brand.setName("kkk");
    	try {
    		brand = productService.addBrand(brand);
    		logger.debug("add brand, id=" + brand.getId());
		} catch (Exception e) {
			logger.error(e);
		}
	}
    
    /**
     * 上传文件(固定使用POST方法)
     */
    @RequestMapping(value = "/update/productinfo", method = RequestMethod.POST)
    public void updateProductInfo(ProductInfo productInfo, HttpServletRequest request, HttpServletResponse response){
    	// 获得文件
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> uploadFiles = multipartRequest.getFileMap();
		try {
			// 获得写入路径
			Properties prop = PropertiesUtils.loadProperties("classpath:project.properties");
			String root = prop.getProperty("productinfo.image");
	        String path = request.getSession().getServletContext().getRealPath(root);
			// 读取文件信息
			for (Entry<String, MultipartFile> bean : uploadFiles.entrySet()) {
				MultipartFile uploadFile = bean.getValue();
				FileBean fileBean = FileUtils.uploadFile(uploadFile.getInputStream(), path, uploadFile.getOriginalFilename());
				productService.updateProductInfo(productInfo, fileBean, path);
			}
        } catch (Exception e) {
        	logger.error(e);
        }
    }
	
}
